<template>
  <section class="todoapp">
    <TodoHeader
    @isAdd="hIsAdd" />
    <TodoMain
    @delData="hDelData"
    @IsChange="hIsChange"
    @changeAll="hChangeAll"
    :list="newList" />
    <TodoFooter
    @isClearDone="hIsClearDone"
    @changeType="hChangeType"
    :list="newList" />
  </section>
</template>

<script>
// 引入组件
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'

export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter
  },
  data() {
    return {
      // list: [
      //   { id: 1, name: '吃饭', isDone: true },
      //   { id: 2, name: '睡觉', isDone: false },
      //   { id: 3, name: '打豆豆', isDone: true }
      // ],
      list: JSON.parse(localStorage.getItem('list') || []),
      type: 'all'
      // form: {
      //   id: '',
      //   name: '',
      //   isDone: ''
      // }
    }
  },
  methods: {
    hDelData(id) {
      const index = this.list.findIndex(item => item.id === id)
      this.list.splice(index, 1)
    },
    hIsChange(num) {
      const obj = this.list.find(item => item.id === num)
    },
    hIsAdd(name) {
      this.list.push({
        id: Date.now(),
        name,
        isDone: false
      })
    },
    hIsClearDone() {
      this.list = this.list.filter(item => !item.isDone)
    },
    hChangeType(type) {
      this.type = type
    },
    hChangeAll(val) {
      this.list.forEach(item => item.isDone = val)
    }
  },
  computed: {
    newList() {
      if(this.type == 'all') {
        return this.list
      } else if (this.type == 'active') {
        return this.list.filter(item => !item.isDone)
      } else if (this.type == 'completed') {
        return this.list.filter(item => item.isDone)
      }
    }
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem('list', JSON.stringify(this.list))
      }
    }
  }
}
</script>

<style></style>
